/**************************************************************
  > File Name: stat_.c
  > Author: LuoLiang
  > Mail: 1204553475@qq.com 
  > Created Time: 2021年12月15日 星期三 19时26分29秒
 **************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>

/*返回文件的大小
 * 
 */

off_t flen(const char *filename)
{
	struct stat statres; 

	if (stat(filename,&statres) < 0)
	{
		perror("stat()");
		exit(1);
	}
	return statres.st_size;
}

/*通过宏来判断文件类型
 *
 */
mode_t file_type(const char *filename)
{
	struct stat statres;

	if (stat(filename,&statres) < 0)
	{
		perror("stat()");
		exit(1);
	}
	
	if (S_ISREG(statres.st_mode))
		return '-';
		else if (S_ISDIR(statres.st_mode))
			return 'd';
			else if (S_ISLNK(statres.st_mode))
				return 'l';
				else
					return '?';
}

/*通过位图判断文件类型
 *
 */

mode_t file_type_bit(const char *filename)
{
	struct stat statres;

	if (stat(filename,&statres) < 0)
	{
		perror("stat()");
		exit(1);
	}
	
	switch (statres.st_mode & S_IFMT)
	{
			case S_IFREG:
				return '-';
			case S_IFDIR:
				return 'd';
			case S_IFLNK:
				return 'l';
			default:
				return '?';
	}

}

char *permission(char *filename)
{
	char *buf = NULL;
	struct stat statres;
	int k = 0;
	int flag = 0;

	buf = calloc(10,sizeof(char));
	if (buf == NULL)
	{
		fprintf(stderr,"calloc()\n");
		exit(1);
	}
	for (int i = 0; i < 9; i++)
	{
		buf[i] = '-';
	}

	if (stat(filename,&statres) < 0)
	{
		perror("stat()");
		exit(1);
	}

	if (statres.st_mode & S_IRUSR)
			buf[k] = 'r';
	if (statres.st_mode & S_IWUSR)
			buf[k+1] = 'w';
	if (statres.st_mode & S_IXUSR)
			buf[k+2] = 'x';

	if (statres.st_mode & S_IRGRP)
			buf[k+3] = 'r';
	if (statres.st_mode & S_IWGRP)
			buf[k+4] = 'w';
	if (statres.st_mode & S_IXGRP)
			buf[k+5] = 'x';

	if (statres.st_mode & S_IROTH)
			buf[k+6] = 'r';
	if (statres.st_mode & S_IWOTH)
			buf[k+7] = 'w';
	if (statres.st_mode & S_IXOTH)
			buf[k+8] = 'x';

	return buf;
}


int main(int argc,char **argv)
{
	if (argc < 2)
	{
		fprintf(stderr,"Usage\n");
		exit(1);
	}
	off_t len = 0;

	len = flen(argv[1]);

	printf("%c%s %ld\n",file_type_bit(argv[1]),permission(argv[1]),len);

    exit(0);
}
